const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})
const dayjs = require('../../miniprogram_npm/miniprogram_npm/dayjs/index')
const util= require('../../utils/util.js')

Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 选择框
        dropdownOption1: [{
                text: '按需求',
                value: 0
            },
            {
                text: '需求最多',
                value: 1
            },
            {
                text: '需求最低',
                value: 2
            },
        ],
        dropdownOption2: [{
                text: '按截止日',
                value: 0
            },
            {
                text: '最晚截止',
                value: 1
            },
            {
                text: '最早截止',
                value: 2
            },
        ],
        dropdownOption3: [{
                text: '按日薪',
                value: 0
            },
            {
                text: '日薪最高',
                value: 1
            },
            {
                text: '日薪最低',
                value: 2
            },
        ],
        dropdownValue1: 0,
        dropdownValue2: 0,
        dropdownValue3: 0,

        // 工作列表
        jobList: [],
        curPage: 0,
        order: "salary",
        sequence: "desc",

        // 修改按钮
        toUpdate: false,
        loading: true,
        loadingCompanyInfo: true,
        // userId
        userId: "",
        isShowEmpty: false,
        companyImg: ''
    },

    // 修改职位信息
    toUpdateJob(e) {
        const jobid = e.currentTarget.dataset.jobid
        this.setData({
            toUpJobPage: true
        })
        wx.redirectTo({
            url: '/pages/upJob/upJob?id=' + jobid + '&companyId=' + this.data.companyId,
        })
    },

    toTakeoffJob(e) {
        wx.showLoading({
          title: '下架中...'
        })
        const jobid = e.currentTarget.dataset.jobid
        db.collection('work_job').doc(jobid).update({
            data: {
                status: 0
            }
        }).then(async res=>{
            this.setData({
                jobList: [],
                curPage: 0,
                loading: true
            })
            await this.getJobList()
            wx.hideLoading()
            util.myToastSuccess('下架成功')
        }).catch(res=>{
            console.log(res)
            wx.hideLoading()
            util.myToastSuccess('下架失败')
        })
    },

    toTakeonJob(e) {
        wx.showLoading({
            title: '上架中...'
          })
          const jobid = e.currentTarget.dataset.jobid
          db.collection('work_job').doc(jobid).update({
              data: {
                  status: 1
              }
          }).then(async res=>{
            this.setData({
                jobList: [],
                curPage: 0,
                loading: true
            })
            wx.hideLoading()
            util.myToastSuccess('上架成功')
            await this.getJobList()
          }).catch(res=>{
              console.log(res)
              wx.hideLoading()
              util.myToastSuccess('上架失败')
          })
    },

    // 前往修改公司信息页面
    toUpdateFirmPage() {
        wx.navigateTo({
            url: '/pages/updateFirm/updateFirm?id=' + this.data.companyId
        })
    },

    async getCompanyInfo(id) {
        const res = await db.collection('work_company').doc(id).get()
        // console.log('res', res.data)
        this.setData({
            address: res.data.address,
            averageSalary: res.data.averageSalary,
            companyName: res.data.companyName,
            introduce: res.data.introduce,
            userId: res.data.userId,
            companyImg: res.data.companyImg,
            companyId: res.data._id,
            category: res.data.category
        })
        // console.log("userID", this.data.userId)
    },

    // 按1搜索
    async onSwitch1Change({
        detail
    }) {
        this.setData({
            dropdownValue1: detail,
            dropdownValue2: 0,
            dropdownValue3: 0,
            loading: true,
            isShowEndline: true,
            jobList: [],
            curPage: 0
        })
        let order = "remainNum"
        let sequence = ""
        if (detail == 1) {
            sequence = "desc"
        } else if (detail == 2) {
            sequence = "asc"
        }
        this.setData({
            order,
            sequence
        })
        await this.getJobList(5, order, sequence)
    },

    // 按2搜索
    async onSwitch2Change({
        detail
    }) {
        this.setData({
            dropdownValue1: 0,
            dropdownValue2: detail,
            dropdownValue3: 0,
            loading: true,
            isShowEndline: true,
            jobList: [],
            curPage: 0
        })
        let order = "endTime"
        let sequence = ""
        if (detail == 1) {
            sequence = "desc"
        } else if (detail == 2) {
            sequence = "asc"
        }
        this.setData({
            order,
            sequence
        })
        await this.getJobList(5, order, sequence)
    },

    // 按3搜索
    async onSwitch3Change({
        detail
    }) {
        this.setData({
            dropdownValue1: 0,
            dropdownValue2: 0,
            dropdownValue3: detail,
            isShowEndline: true,
            jobList: [],
            curPage: 0
        })
        let order = "salary"
        let sequence = ""
        if (detail == 1) {
            sequence = "desc"
        } else if (detail == 2) {
            sequence = "asc"
        }
        this.setData({
            order,
            sequence
        })
        await this.getJobList(5, order, sequence)
    },

    async getJobList(limit = 10, order = "salary", sequence = "desc") {
        let page = this.data.curPage
        let res = {}
        // 普通用户进入
        if (!this.data.toUpdate) {
            db.collection('work_job').skip(page * limit).limit(limit).where({
                userId: this.data.userId,
                status: 1
            }).orderBy(order, sequence).get().then(res=>{
                res.data.forEach(job=>{
                    job.endTime = dayjs(job.endTime).format("YYYY-MM-DD")
                })
                console.log(res.data)
                this.setData({
                    jobList: this.data.jobList.concat(res.data),
                    loading: false
                })
                if (this.data.jobList.length === 0) {
                    this.setData({isShowEmpty: true})
                }
            })
        } else { // 公司管理者进入
            res = await db.collection('work_job').skip(page * limit).orderBy('status', 'desc').orderBy(order, sequence).limit(limit)
                .where({
                    userId: this.data.userId
                }).get()
            let jobList = res.data
            for (let i = 0; i < jobList.length; i++) {
                const job = jobList[i]
                jobList[i].isUped = job.status === 1 ? true : false
                jobList[i].endTime = dayjs(job.endTime).format("YYYY-MM-DD")
            }
            // 重新排序
            let old = this.data.jobList
            jobList = old.concat(jobList)
            function sortRule(a,b) {
                return b.status - a.status
            }
            jobList.sort(sortRule)
            this.setData({
                jobList: jobList,
                loading: false
            })
            if (this.data.jobList.length === 0) {
                this.setData({isShowEmpty: true})
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        // 公司所有者进入该页面
        if (options.toUpdate) {
            this.setData({
                toUpdate: true,
                companyId: options.id
            })
        }
        await this.getCompanyInfo(options.id)
        this.setData({
            loadingCompanyInfo: false
        })
        await this.getJobList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (this.data.companyId) {
            this.getCompanyInfo(this.data.companyId)
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        setTimeout(() => {
            wx.hideNavigationBarLoading()
            // 数据成功后，停止下拉刷新
            wx.stopPullDownRefresh()
        }, 600)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        wx.showLoading({
            title: '加载中..',
        })
        this.setData({
            curPage: this.data.curPage + 1
        })
        this.getJobList(5, this.data.order, this.data.sequence).then(() => {
            // 数据成功后，停止下拉刷新
            wx.stopPullDownRefresh()
            wx.hideLoading()
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    toJobDetailPage(e) {
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + e.currentTarget.dataset.id + '&fromFirmPage=1'
        })
    },
})